import { useState, useEffect, ChangeEvent } from "react";
import axios, { AxiosError } from "axios";
import { useParams, useNavigate } from "react-router-dom";

const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || "http://localhost:5001";

interface DatasetDetail {
  name: string;
  // Add other dataset properties if needed
}

interface ApiErrorData {
  error?: string;
}

const UploadDocument = () => {
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [datasetName, setDatasetName] = useState<string>("");
  const [error, setError] = useState<string | null>(null);
  const [uploading, setUploading] = useState<boolean>(false);
  const [uploadSuccess, setUploadSuccess] = useState<boolean>(false);
  const { datasetId } = useParams<{ datasetId: string }>(); // Get datasetId from URL and type it
  const navigate = useNavigate();

  useEffect(() => {
    const fetchDatasetDetails = async () => {
      if (!datasetId) return;
      try {
        const response = await axios.get<DatasetDetail>(`${API_BASE_URL}/datasets/${datasetId}`);
        setDatasetName(response.data.name);
      } catch (err: any) { // It"s better to type err more specifically if possible
        console.error("Error fetching dataset details:", err);
        setError("加载知识库详情失败。");
      }
    };
    fetchDatasetDetails();
  }, [datasetId]);

  const handleFileChange = (event: ChangeEvent<HTMLInputElement>) => {
    if (event.target.files && event.target.files[0]) {
      setSelectedFile(event.target.files[0]);
    } else {
      setSelectedFile(null);
    }
    setUploadSuccess(false);
    setError(null);
  };

  const handleUpload = async () => {
    if (!selectedFile) {
      setError("请先选择一个文件。");
      return;
    }
    if (!datasetId) {
      setError("未指定知识库ID。");
      return;
    }

    setUploading(true);
    setError(null);
    setUploadSuccess(false);

    const formData = new FormData();
    formData.append("file", selectedFile);

    try {
      const response = await axios.post(`${API_BASE_URL}/datasets/${datasetId}/documents`, formData, {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      });
      console.log("File uploaded successfully:", response.data);
      setUploadSuccess(true);
      setSelectedFile(null); // Clear the file input
      // Optionally, navigate away or refresh data
    } catch (err) {
      console.error("Error uploading file:", err);
      const axiosError = err as AxiosError<ApiErrorData>; // Type assertion
      if (axiosError.response) {
        setError(`上传失败: ${axiosError.response.status} - ${axiosError.response.data?.error || "服务器错误"}`);
      } else if (axiosError.request) {
        setError("服务器无响应，请检查后端服务是否运行。");
      } else {
        setError("上传请求时发生错误。");
      }
    } finally {
      setUploading(false);
    }
  };

  if (!datasetId) {
    return <p>请先从知识库列表选择一个知识库进行操作。</p>;
  }

  return (
    <div>
      <h2>上传文档到知识库: {datasetName || datasetId}</h2>
      <div>
        <input type="file" onChange={handleFileChange} />
        <button onClick={handleUpload} disabled={uploading || !selectedFile}>
          {uploading ? "正在上传..." : "上传文档"}
        </button>
      </div>
      {error && <p style={{ color: "red" }}>{error}</p>}
      {uploadSuccess && <p style={{ color: "green" }}>文档上传成功！</p>}
      <button onClick={() => navigate("/datasets")} style={{ marginTop: "1rem" }}>返回知识库列表</button>
    </div>
  );
};

export default UploadDocument;

